﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.ComponentModel;
using System.Reflection;
using YAPSAR.Native;

namespace YAPSAR.Collector
{
    public class KeyListener
    {
        /// <summary>
        /// Destruction.
        /// </summary>
        ~KeyListener()
        {
            //uninstall hooks and do not throw exceptions
            Stop(false);
        }

        /// <summary>
        /// Occurs when the user presses a key
        /// </summary>
        public event KeyEventHandler KeyDown;

        /// <summary>
        /// Occurs when the user presses and releases 
        /// </summary>
        public event KeyPressEventHandler KeyPress;

        /// <summary>
        /// Occurs when the user releases a key
        /// </summary>
        public event KeyEventHandler KeyUp;

        /// <summary>
        /// Stores the handle to the keyboard hook procedure.
        /// </summary>
        private int hKeyboardHook = 0;

        /// <summary>
        /// Declare KeyboardHookProcedure as HookProc type.
        /// </summary>
        private static UnsafeMethods.HookProc KeyboardHookProcedure;

        public bool IsActive = false;
        /// <summary>
        /// Installs both or one of mouse and/or keyboard hooks and starts rasing events
        /// </summary>
        /// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
        /// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
        /// <exception cref="Win32Exception">Any windows problem.</exception>
        public void Start()
        {
            IsActive = true;
            
            // install Keyboard hook only if it is not installed and must be installed
            if (hKeyboardHook == 0)
            {
                // Create an instance of HookProc.
                KeyboardHookProcedure = new UnsafeMethods.HookProc(KeyboardHookProc);
                //install hook
                hKeyboardHook = UnsafeMethods.SetWindowsHookEx(UnsafeConstants.WH_KEYBOARD_LL, KeyboardHookProcedure, IntPtr.Zero, 0);
                //If SetWindowsHookEx fails.
                if (hKeyboardHook == 0)
                {
                    //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
                    int errorCode = Marshal.GetLastWin32Error();
                    //do cleanup
                    Stop(false);
                    //Initializes and throws a new instance of the Win32Exception class with the specified error. 
                    throw new Win32Exception(errorCode);
                }
            }
        }

        /// <summary>
        /// Stops monitoring both or one of mouse and/or keyboard events and rasing events.
        /// </summary>
        /// <param name="UninstallMouseHook"><b>true</b> if mouse hook must be uninstalled</param>
        /// <param name="UninstallKeyboardHook"><b>true</b> if keyboard hook must be uninstalled</param>
        /// <param name="ThrowExceptions"><b>true</b> if exceptions which occured during uninstalling must be thrown</param>
        /// <exception cref="Win32Exception">Any windows problem.</exception>
        public void Stop(bool ThrowExceptions)
        {
            IsActive = false;

            //if keyboard hook set and must be uninstalled
            if (hKeyboardHook != 0)
            {
                //uninstall hook
                int retKeyboard = UnsafeMethods.UnhookWindowsHookEx(hKeyboardHook);
                //reset invalid handle
                hKeyboardHook = 0;
                //if failed and exception must be thrown
                if (retKeyboard == 0 && ThrowExceptions)
                {
                    //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. 
                    int errorCode = Marshal.GetLastWin32Error();
                    //Initializes and throws a new instance of the Win32Exception class with the specified error. 
                    throw new Win32Exception(errorCode);
                }
            }
        }

        /// <summary>
        /// A callback function which will be called every time a keyboard activity detected.
        /// </summary>
        /// <param name="nCode">
        /// [in] Specifies whether the hook procedure must process the message. 
        /// If nCode is HC_ACTION, the hook procedure must process the message. 
        /// If nCode is less than zero, the hook procedure must pass the message to the 
        /// CallNextHookEx function without further processing and must return the 
        /// value returned by CallNextHookEx.
        /// </param>
        /// <param name="wParam">
        /// [in] Specifies whether the message was sent by the current thread. 
        /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero. 
        /// </param>
        /// <param name="lParam">
        /// [in] Pointer to a CWPSTRUCT structure that contains details about the message. 
        /// </param>
        /// <returns>
        /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx. 
        /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx 
        /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC 
        /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook 
        /// procedure does not call CallNextHookEx, the return value should be zero. 
        /// </returns>
        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            //indicates if any of underlaing events set e.Handled flag
            bool handled = false;
            //it was ok and someone listens to events
            if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
            {
                //read structure KeyboardHookStruct at lParam
                UnsafeStructs.KeyboardHookStruct MyKeyboardHookStruct =
                    (UnsafeStructs.KeyboardHookStruct) Marshal.PtrToStructure(lParam, typeof (UnsafeStructs.KeyboardHookStruct));
                //raise KeyDown
                if (KeyDown != null && (wParam == UnsafeConstants.WM_KEYDOWN || wParam == UnsafeConstants.WM_SYSKEYDOWN))
                {
                    Keys keyData = (Keys) MyKeyboardHookStruct.vkCode;
                    KeyEventArgs e = new KeyEventArgs(keyData);
                    KeyDown(this, e);
                    handled = handled || e.Handled;
                }

                // raise KeyPress
                if (KeyPress != null && wParam == UnsafeConstants.WM_KEYDOWN)
                {
                    bool isDownShift = ((UnsafeMethods.GetKeyState(UnsafeConstants.VK_SHIFT) & 0x80) == 0x80 ? true : false);
                    bool isDownCapslock = (UnsafeMethods.GetKeyState(UnsafeConstants.VK_CAPITAL) != 0 ? true : false);
                    bool isDownControl = (UnsafeMethods.GetKeyState(UnsafeConstants.VK_CAPITAL) != 0 ? true : false);
                    bool isDownAlt = (UnsafeMethods.GetKeyState(UnsafeConstants.VK_ALT) != 0 ? true : false);

                    byte[] keyState = new byte[256];
                    UnsafeMethods.GetKeyboardState(keyState);
                    byte[] inBuffer = new byte[2];
                    if (UnsafeMethods.ToAscii(MyKeyboardHookStruct.vkCode,
                                MyKeyboardHookStruct.scanCode,
                                keyState,
                                inBuffer,
                                MyKeyboardHookStruct.flags) == 1)
                    {
                        char key = (char) inBuffer[0];
                        if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key);
                        KeyPressEventArgs e = new KeyPressEventArgs(key);
                        KeyPress(this, e);
                        handled = handled || e.Handled;
                    }
                }

                // raise KeyUp
                if (KeyUp != null && (wParam == UnsafeConstants.WM_KEYUP || wParam == UnsafeConstants.WM_SYSKEYUP))
                {
                    Keys keyData = (Keys) MyKeyboardHookStruct.vkCode;
                    KeyEventArgs e = new KeyEventArgs(keyData);
                    KeyUp(this, e);
                    handled = handled || e.Handled;
                }

            }

            //if event handled in application do not handoff to other listeners
            if (handled)
                return 1;
            else
                return UnsafeMethods.CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
        }
    }
}
